import { cloneDeep } from 'lodash-es'
import { http } from '@/utils/http'
import { ElMessage, ElMessageBox } from 'element-plus'
// import { useHomeStore } from './home-store.js'

import _ from 'lodash-es'



export const useMonitorStore = () => {
    const router = useRouter()
    // const homestore = useHomeStore()
    const state = reactive({
        ismoutned: false,
        buttonshow: true,
        buttonshow2: true,
        search_form: {
            bc_type: '',
            date: 'all',
            pk_types: [],
            league_id: '',
            match_id: '',
            home_id: '',
            away_id: '',
            hours: 24,
            order_by: 1
        },
        SearchHandicap: [
            {
                label: '让球',
                value: 'R'
            }, {
                label: '大小',
                value: 'OU'
            }, {
                label: '独赢',
                value: 'M'
            }
        ],
        searchLeague: [],
        searchMatchs: [],
        handicapTypes: [
            {
                label: '让球',
                value: 'R'
            }, {
                label: '半让球',
                value: 1
            }, {
                label: '大小',
                value: 'OU'
            }, {
                label: '半大小',
                value: 3
            }, {
                label: '独赢',
                value: 'M'
            }, {
                label: '半独赢',
                value: 5
            }
        ],
        bctypesObj: {},
        activehandicapType: 0,
        activehandicap: 0,
        handicaps: [
            {
                value: 0,
                label: '无走势',
                count: 7
            }, {
                value: 1.5,
                label: '1.5',
                count: 19
            }, {
                value: 1.75,
                label: '1.75',
                count: 7
            }, {
                value: 2,
                label: '2.0',
                count: 7
            }, {
                value: 2.25,
                label: '2.25',
                count: 7
            }, {
                value: 2.5,
                label: '2.5',
                count: 7
            }, {
                value: 2.75,
                label: '2.75',
                count: 7
            }, {
                value: 3,
                label: '3.0',
                count: 7
            }, {
                value: 3.25,
                label: '3.25',
                count: 7
            }, {
                value: 3.5,
                label: '3.5',
                count: 7
            }, {
                value: 3.75,
                label: '3.75',
                count: 7
            }, {
                value: 4,
                label: '4.0',
                count: 7
            },
        ],
        timeSelects: [
            {
                value: 'second5',
                label: '5秒',
                num: 5
            }, {
                value: 'second10',
                label: '10秒',
                num: 10
            }, {
                value: 'second30',
                label: '30秒',
                num: 30
            }, {
                value: 'minute1',
                label: '1分钟',
                num: 60
            }, {
                value: 'minute10',
                label: '10分钟',
                num: 600
            }, {
                value: 'minute30',
                label: '30分钟',
                num: 1800
            }, {
                value: 'hour1',
                label: '1小时',
                num: 3600
            },
        ],
        activeTime: 'second5',

        matchdialog: {
            data: []
        },

        filterData: [],
        editionData: {},
        riseBctype: 'hga',
        riseHours: 24,
        fallBctype: 'hga',
        fallHours: 24,

        isallbctypes: false,

        showmonitordialog: false,
        activemonitor: {},
        activemonitortab: 0,
        monitordata: [],

        checkpictureHandicap: {},

        picturedata: {
            picture_data_obj: {},
            picture_filter: {}
        },
        copypicturedata: {},

        collectordata: [],
        echart: null,
        chartmodule: {
            activeTime: 'second5',
            checkpicturelist: [],
            activeHandicaps: {},
            copyActiveHandicaps: {},
            match: {},

            data: {
                header: [],
                data: []
            }
        },
        showtrend: true,

        ispicturdata: null,
        ispicturdatanum: 0,



        pictureLoading: true
    })

    const changeHandicaptype = (value) => {
        state.activehandicapType = value
    }

    const changeactivetime = (value) => {
        state.activeTime = value
    }

    const openMatchDialog = (row) => {
        let b = {
            index: state.matchdialog.data.length + 1,
            show: true,
            position: { x: 100 + state.matchdialog.data.length * 20, y: 100 + state.matchdialog.data.length * 20 },
            zindex: 2000 + state.matchdialog.data.length,
            dragging: false,
            offsetX: 0,
            offsetY: 0,
            ref: null,
            data: row
        }
        state.matchdialog.data.push(b)

    }

    const clickMatchDialog = (item) => {
        let maxZIndexObject = state.matchdialog.data.sort((a, b) => b.zindex - a.zindex)[0];
        let maxIndex = maxZIndexObject.zindex
        let itemIndex = item.zindex
        item.zindex = maxIndex
        maxZIndexObject.zindex = itemIndex
    }

    const getSearchHandicap = () => {
        http.get('/zhishu/get_pk_key_data').then((res) => {

        })
    }

    const changebctype = () => {
        if (state.search_form.bc_type == 'all') {
            state.searchLeague = []
        } else {
            let body = {
                params: {
                    bc_type: state.search_form.bc_type
                }
            }
            if (state.search_form.date != 'all') {
                body.params.date = state.search_form.date
            }
            http.get('/zhishu/get_league_infos', body).then((res) => {
                let a = []
                Object.values(res).forEach(item => {
                    let b = {
                        value: item.league_id,
                        label: item.league_name,
                        matchs: item.matchs
                    }
                    a.push(b)
                });

                state.searchLeague = a
            })
        }

    }

    const changeleague = () => {
        if (state.search_form.league_id == 'all') {
            state.searchMatchs = []
        } else {
            let a = []
            state.searchLeague.forEach(item => {
                if (item.value == state.search_form.league_id) {
                    item.matchs.forEach(item2 => {
                        let b = {
                            value: `${item2.home_id}^${item2.away_id}`,
                            label: `${item2.home_name}-${item2.away_name}`
                        }
                        a.push(b)
                    });
                }
            });
            state.searchMatchs = a
        }
    }

    const getsavefilter = (show) => {
        state.buttonshow = show
        let body = JSON.parse(JSON.stringify(state.search_form))
        if (body.date == '') {
            body.date = 'all'
        }
        if (body.match_id == 'all') {
            body.home_id = 'all'
            body.away_id = 'all'
        } else {
            const match = body.match_id.match(/^(.*?)\^(.*)$/);
            if (match) {
                body.home_id = match[1];
                body.away_id = match[2];
            }
        }
        delete body.match_id

        http.post('/zhishu/save_zhishu_filter', body).then((res) => {
            state.buttonshow = true
            state.buttonshow2 = true
        }).catch(() => {
            state.buttonshow = true
            state.buttonshow2 = true
        })

    }

    const handleCommand = (command) => {
        state.search_form.hours = command
    }
    const handleCommandFall = (command) => {
        state.fallHours = command
    }
    const handleCommandRise = (command) => {
        state.riseHours = command
    }

    const getsearchLeague = () => {

    }

    const getbctypes = () => {
        let a = {}
        let b = JSON.parse(localStorage.userInfo)
        if (b.products.data_feed) {
            b.products.data_feed.list.forEach(item => {
                a[item.attr_code] = item.attr_name
            });
        }
        state.bctypesObj = a
    }

    const clickCollect = (row) => {
        http.post('/zhishu/save_collect', row).then((res) => {
            ElMessage({
                message: '收藏成功',
                type: 'success',
            })
        })
    }

    const clickCancelcollect = (row) => {
        let params = {
            ids: row.ids,
            bc_type: row.bc_type,
            pk_odds_key: row.pk_odds_key
        }
        http.delete('/zhishu/del_collect', { params: params }).then((res) => {
            ElMessage({
                message: '取消收藏成功',
                type: 'success',
            })
        })
    }

    const savepicture = (row) => {
        console.log(row);




        getmatchallpk(row)

        // state.isallbctypes = true
        // http.post('/zhishu/save_picture', row).then((res) => {
        //     state.pictureLoading = true
        // })
    }

    const changecheckpicture = () => {
        let data = []
        let data2 = {
            header: [],
            data: []
        }

        state.chartmodule.checkpicturelist.forEach(item => {
            let value = state.chartmodule.activeHandicaps[item].childrens[state.chartmodule.activeHandicaps[item].activetab].index_data[state.chartmodule.activeTime][state.chartmodule.activeHandicaps[item].active]
            data.push(value)

        });



        data.forEach(item => {
            if (item != undefined) {
                let a = []
                item.forEach(item2 => {
                    data2.header.push(item2.date)
                    a.push(item2.odd)
                });
                data2.data.push(a)
            }

        });


        state.chartmodule.data = data2

        if (state.copypicturedata.picture_filter) {


            if (state.copypicturedata.picture_filter.ids == state.picturedata.picture_filter.ids) {
                state.copypicturedata = JSON.parse(JSON.stringify(state.picturedata))


                if (state.echart != null && state.showtrend) {
                    state.pictureLoading = false
                    state.showtrend = true
                    state.echart.getEcharts()
                    // state.echart.updateChart()
                    // state.showtrend = false

                    // setTimeout(() => {
                    //     state.showtrend = true
                    //     state.echart.getEcharts()
                    // }, 100);
                }

            } else {
                state.copypicturedata = JSON.parse(JSON.stringify(state.picturedata))
                state.pictureLoading = true
                state.showtrend = false

                setTimeout(() => {
                    state.showtrend = true
                    state.pictureLoading = false
                    state.echart.getEcharts()
                    // state.echart.updateChart()
                }, 500);
            }
        } else {
            state.copypicturedata = JSON.parse(JSON.stringify(state.picturedata))

            state.pictureLoading = false

            if (state.echart != null && state.showtrend) {
                state.echart.getEcharts()
                // state.echart.updateChart()
            }
        }

        // console.log(state.chartmodule.data);



    }

    const refactPicturedata = () => {
        let a = []
        let b = {}
        Object.keys(state.picturedata.picture_data_obj).forEach(key => {
            if (state.bctypesObj[key] != undefined) {
                let value = state.picturedata.picture_data_obj[key]
                let onekey = Object.keys(value)[0]
                if (isEmpty(value[onekey].index_data.second5)) {
                } else {

                    if (state.copypicturedata.picture_filter && state.picturedata.picture_filter && (state.copypicturedata.picture_filter.ids != state.picturedata.picture_filter.ids || state.copypicturedata.picture_filter.pk_odds_key != state.picturedata.picture_filter.pk_odds_key)) {
                        state.chartmodule.activeHandicaps[key] = {
                            activetab: '',
                            activetab2: '',
                            active: '',
                            childrens: {}
                        }
                    }

                    if (state.chartmodule.activeHandicaps[key] == null || state.chartmodule.activeHandicaps[key].active == '') {
                        state.chartmodule.activeHandicaps[key] = {
                            activetab: '',
                            activetab2: '',
                            active: '',
                            childrens: {}
                        }
                    } else {
                        state.chartmodule.activeHandicaps[key].childrens = {}
                    }




                    if (value[state.chartmodule.activeHandicaps[key].activetab] == undefined || value[state.chartmodule.activeHandicaps[key].activetab].index_data.second5[state.chartmodule.activeHandicaps[key].active] == undefined) {
                        state.chartmodule.activeHandicaps[key] = {
                            activetab: '',
                            activetab2: '',
                            active: '',
                            childrens: {}
                        }
                    }



                    Object.keys(value).forEach(key2 => {
                        let value2 = value[key2]

                        if (isEmpty(value2.index_data)) {
                        } else {
                            state.chartmodule.activeHandicaps[key].childrens[value2.header_key] = value2

                            if (state.chartmodule.activeHandicaps[key].active == '') {
                                let value3 = value2.index_data.second5
                                state.chartmodule.activeHandicaps[key].active = state.picturedata.picture_filter.type_name
                                state.chartmodule.activeHandicaps[key].activetab = state.picturedata.picture_filter.pk_name
                                state.chartmodule.activeHandicaps[key].activetab2 = state.picturedata.picture_filter.pk_name

                            }
                            b[key] = state.chartmodule.activeHandicaps[key]
                        }

                    })

                    if (state.chartmodule.activeHandicaps[key] && value[state.chartmodule.activeHandicaps[key].activetab] != undefined && value[state.chartmodule.activeHandicaps[key].activetab].index_data.second5[state.chartmodule.activeHandicaps[key].active] != undefined) {
                        a.push(key)
                    } else {
                        console.log(state.chartmodule.activeHandicaps);

                        ElMessage({
                            message: '无法找到当前盘口',
                            type: 'warning',
                        })

                    }


                }

            }

        });


        state.chartmodule.activeHandicaps = {}
        Object.keys(b).forEach(key => {
            let value = b[key]
            if (value.childrens[value.activetab].index_data.second5[value.active]) {
                state.chartmodule.activeHandicaps[key] = value
            }
        })


        let c = 0
        state.chartmodule.checkpicturelist.forEach(item => {
            if (a.includes(item)) {
            } else {
                c = -1
            }
        });


        console.log(state.chartmodule.checkpicturelist);

        if (state.chartmodule.checkpicturelist.length > 0 && c != -1 && !state.isallbctypes) {
            // state.chartmodule.checkpicturelist = a
            changecheckpicture()
        } else {
            state.chartmodule.checkpicturelist = a
            state.isallbctypes = false
            changecheckpicture()
        }



    }
    // 判断一个对象是否为空对象
    const isEmpty = (obj) => {
        return Object.keys(obj).length === 0;
    }

    const clickreset = () => {
        state.buttonshow2 = false
        state.search_form = {
            bc_type: 'all',
            date: 'all',
            pk_types: ['R', 'OU'],
            league_id: 'all',
            match_id: 'all',
            home_id: '',
            away_id: '',
            hours: 24,
            order_by: 1
        }
        getsavefilter(true)
    }

    const addmonitor = () => {
        state.activemonitor = {}
        state.showmonitordialog = true

    }

    const editmonitor = (row) => {
        state.activemonitor = row
        state.showmonitordialog = true

    }

    const getmatchallpk = (row) => {
        // console.log(row);

        state.chartmodule.match = JSON.parse(JSON.stringify(row))
        let body = {
            bc_type: row.bc_type,
            league_id: row.league_id,
            home_id: row.home_id,
            away_id: row.away_id,
            ids: row.ids,
            pk_odds_key: row.pk_odds_key,
            pk_odds_key_ch: row.pk_odds_key_ch
        }
        state.chartmodule.activeHandicaps = {}
        state.pictureLoading = true
        http.post('/zhishu/get_match_all_pk', body).then((res) => {
            if (res != null) {
                // state.chartmodule.activeHandicaps = res
                state.chartmodule.checkpicturelist = []
                let a = {}
                if (isEmpty(res)) {
                } else {
                    Object.keys(res).forEach(key => {
                        if (state.bctypesObj[key]) {
                            a[key] = {
                                activetab: '',
                                activetabvalue: '',
                                activevalue: '',
                                activelabel: '',
                                ids: '',
                                childer: res[key]
                            }
                            Object.keys(res[key]).forEach(key2 => {
                                if (row.pk_odds_key.includes(key2)) {
                                    let value2 = res[key][key2]
                                    a[key].ids = value2.ids
                                    Object.keys(value2.pk_list).forEach(key3 => {
                                        let value3 = value2.pk_list[key3]
                                        if (value3 == row.pk_odds_key) {
                                            state.chartmodule.checkpicturelist.push(key)
                                            a[key].activetab = key2
                                            a[key].activetabvalue = key2
                                            a[key].activevalue = key3
                                            a[key].activelabel = value3
                                        }
                                    })
                                }
                            })

                            if (a[key].activetab == '') {
                                a[key].activetab = Object.keys(res[key])[0]

                            }
                        }

                    });
                }



                state.chartmodule.activeHandicaps = a
                getpicturedata(true)
            }


        }).catch(() => {
            state.pictureLoading = false
        })
    }

    const getpicturedata = (show) => {
        clearInterval(state.ispicturdata)
        state.pictureLoading = show
        let body = []
        Object.keys(state.chartmodule.activeHandicaps).forEach(key => {
            let value = state.chartmodule.activeHandicaps[key]
            if (value.activelabel != '') {
                body.push({
                    bc_type: key,
                    ids: value.ids,
                    pk_odds_key: value.activelabel
                })
            }
        })


        if (body.length == 0) {
            ElMessage({
                message: '请选择盘口',
                type: 'warning',
            })
            state.picturedata = []
            state.pictureLoading = false
            state.echart.updateChart()
            return;
        }
        http.post(`/zhishu/get_new_picture_data?_=${Date.now()}`, body).then((res) => {
            clearInterval(state.ispicturdata)
            if (state.ismoutned) {
                state.picturedata = res
                state.pictureLoading = false
                getechartsData()
            }

        })

    }

    const getechartsData = () => {
        let num = 5
        state.timeSelects.forEach(item => {
            if (item.value == state.chartmodule.activeTime) {
                num = item.num
            }
        });
        state.picturedata.forEach(item => {
            if (item.history_odds_detail.length > 0) {
                item.data = generateChartData(item.history_odds_detail, num)
                // let a = []
                // item.history_odds_detail.forEach(item2 => {
                //     a.push({
                //         time: formatTimestamp(item2.time),
                //         odds: item2.odds
                //     })
                // });
                // console.log(a);
            } else {
                item.data = []
            }

        });

        // console.log(state.picturedata);




        clearInterval(state.ispicturdata)
        refgetpicturedata()
        state.echart.updateChart()




    }

    const refgetpicturedata = () => {
        clearInterval(state.ispicturdata)
        state.ispicturdata = setInterval(() => getpicturedata(false), 5000)
    }

    function formatTimestamp(timestamp) {

        const date = new Date(timestamp * 1000); // 创建Date对象

        const year = date.getFullYear(); // 获取年份
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 获取月份（注意：月份从0开始）
        const day = String(date.getDate()).padStart(2, '0'); // 获取日期
        const hours = String(date.getHours()).padStart(2, '0'); // 获取小时
        const minutes = String(date.getMinutes()).padStart(2, '0'); // 获取分钟
        const seconds = String(date.getSeconds()).padStart(2, '0'); // 获取秒数
        // ${year}-${month}-${day} 
        // 返回格式化后的时间字符串
        return `${hours}:${minutes}:${seconds}`;
    }
    // **时间对齐到最近的时间间隔**
    function alignTime(timestamp, interval) {
        // return Math.floor(timestamp / interval) * interval;
        return timestamp
    }
    function generateChartData(data, interval) {
        data.sort((a, b) => a.time - b.time);
        // console.log(data);

        let alignedData = [];
        let lastValue = null;
        let minTime = alignTime(data[0].time, interval);
        let maxTime = alignTime(Math.floor(Date.now() / 1000), interval);
        let num = 0

        for (let t = minTime; t <= (maxTime + interval - 10); t += interval) {
            num += 1
            // let current = data.find(d => d.time === t) || lastValue;
            let current = data.find((d, index) => {
                return (
                    (index != data.length - 1 && d.time <= t && data[index + 1].time >= t) ||
                    (index == data.length - 1 && data[index].time <= t)
                );
            }) || lastValue;

            if (current) {
                if (t > maxTime) {
                    alignedData.push({
                        time: formatTimestamp(maxTime),
                        odds: current.odds
                    });
                } else {
                    alignedData.push({
                        time: formatTimestamp(t),
                        odds: current.odds
                    });
                }

                lastValue = current;
            }
        }


        let a = []
        if (alignedData.length > 100) {
            a = alignedData.slice(-100)
            // a = alignedData
        } else {
            a = alignedData
        }
        return a;
    }
    const recudata = (time1, time2, odd) => {

    }
    onMounted(async () => {
        state.ismoutned = true
        state.isallbctypes = true
        initData()
    })

    onUnmounted(() => {
        state.ismoutned = false
        clearInterval(state.ispicturdata)
    })


    async function initData() {
        getSearchHandicap()
        getbctypes()
    }


    return {
        state,


        changeHandicaptype,
        changeactivetime,
        openMatchDialog,
        clickMatchDialog,

        changebctype,
        changeleague,
        getsavefilter,
        handleCommand,
        handleCommandFall,
        handleCommandRise,
        clickCollect,
        clickCancelcollect,
        savepicture,
        changecheckpicture,
        refactPicturedata,
        isEmpty,
        clickreset,
        editmonitor,
        addmonitor,
        getpicturedata,
        getechartsData

    }
}
